package com.daisuxia.web.controller;

import static com.daisuxia.web.pojo.BorrowOrder.STATUS_BFHK;
import static com.daisuxia.web.pojo.BorrowOrder.STATUS_CSTG;
import static com.daisuxia.web.pojo.BorrowOrder.STATUS_DCS;
import static com.daisuxia.web.pojo.BorrowOrder.STATUS_FKSB;
import static com.daisuxia.web.pojo.BorrowOrder.STATUS_FKZ;
import static com.daisuxia.web.pojo.BorrowOrder.STATUS_FSTG;
import static com.daisuxia.web.pojo.BorrowOrder.STATUS_HKZ;
import static com.daisuxia.web.pojo.BorrowOrder.STATUS_YHZ;
import static com.daisuxia.web.pojo.BorrowOrder.STATUS_YYQ;
import static com.daisuxia.web.pojo.BorrowOrder.borrowStatusMap_front;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.daisuxia.back.utils.RequestUtils;
import com.daisuxia.web.common.reslult.Status;
import com.daisuxia.web.pojo.BorrowOrder;
import com.daisuxia.web.pojo.User;
import com.daisuxia.web.pojo.UserCardInfo;
import com.daisuxia.web.pojo.UserOrder;
import com.daisuxia.web.service.IBorrowOrderService;
import com.daisuxia.web.service.IRepaymentService;
import com.daisuxia.web.service.IUserBankService;
import com.daisuxia.web.service.IUserOrderService;
import com.daisuxia.web.util.JSONUtil;
import com.daisuxia.web.util.PageConfig;

/**
 * 用户借款记录
 * 
 * @author dxp
 * @date 2016年12月9日 16:51:09
 * @param
 */
@Controller
public class UserloanDetailController extends BaseController {
	Logger logger = Logger.getLogger(getClass());

	@Autowired
	private IUserOrderService userOrderService;
	@Autowired
	private IBorrowOrderService borrowOrderService;
	@Autowired
	private IRepaymentService repaymentService;

	@Autowired
	private IUserBankService userBankService;

	/**
	 * 获取用户个人中心借款列表
	 * 
	 * @param request
	 * @param response
	 * @param model
	 */

	@RequestMapping("credit-loan/get-my-orders")
	public void getMyOrders(HttpServletRequest request,HttpServletResponse response, Model model) {
		Map<String, Object> json = new HashMap<String, Object>();
		HashMap<String, Object> params = this.getParametersO(request);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String code = Status.FAILD.getName();
		String msg = "获取失败";
		try {
			User user = this.loginFrontUserByDeiceId(request);
			if (user != null) {
				List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();

				if (request.getParameter("page") != null) {
					Integer pageNo = Integer.valueOf(request.getParameter("page"));
					params.put("pageNum", pageNo);
				}
				if (request.getParameter("page") != null) {
					Integer pageSize = Integer.valueOf(request.getParameter("pagsize"));
					params.put("numPerPage", pageSize);
				}

//				params.put("statusList", Arrays.asList(BorrowOrder.STATUS_HKZ,BorrowOrder.STATUS_DCS,BorrowOrder.STATUS_CSTG,BorrowOrder.STATUS_FSBH,BorrowOrder.STATUS_FKBH,
//						  BorrowOrder.STATUS_YYQ,BorrowOrder.STATUS_YHZ,
//						BorrowOrder.STATUS_YHK, BorrowOrder.STATUS_FKSB,BorrowOrder.STATUS_FKZ,BorrowOrder.STATUS_CSBH));
				params.put("userId", user.getId());
				PageConfig<BorrowOrder> page = borrowOrderService
						.findPage(params);

				List<BorrowOrder> pageList = page.getItems();
				if (pageList != null && pageList.size() > 0) {
					Map<String, Object> dataMap = null;
					for (BorrowOrder useO : pageList) {
						String statusName = borrowStatusMap_front.get(useO.getStatus().intValue());
//						if (borrowStatusMap_fangkanSucee.containsKey(useO
//								.getStatus().intValue())) {
//							statusName = "等待还款";
//						} else if (borrowStatusMap_shenhezhong.containsKey(useO
//								.getStatus().intValue())) {// 机审拒绝、待初审、待复审、待放款审核
//							statusName = "审核中";
//						} else if (borrowStatusMap_shenheFail.containsKey(useO
//								.getStatus().intValue())) {// 初审驳回、复审驳回,放款驳回
//							statusName = "审核失败";
//						} else if (borrowStatusMap_yiyuqi.containsKey(useO
//								.getStatus().intValue())) {// 逾期、坏账
//							statusName = "已逾期";
//						} else if (borrowStatusMap_finish.containsKey(useO
//								.getStatus().intValue())) {// 逾期、坏账
//							statusName = "已还款";
//						} else {
//							statusName = useO.getStatusName();
//						}
                        
						dataMap = new HashMap<String, Object>();
						dataMap.put("text",
								"<font color='#ff8003' size='3'>"
										+ statusName + "</font>");
						dataMap.put("time", sdf.format(useO.getCreatedAt()));
						dataMap.put("title", "借款" + new DecimalFormat("0.00").format(useO.getMoneyAmount()/100)+"元");
//						dataMap.put("url",
//								RequestUtils.getRequestPath(null)
//										+ "/mobile/web/loan/loan-detail?id="
//										+ useO.getId());
						dataMap.put("url",
								RequestUtils.getRequestPath(null)
										+ "/repayment/detail.do?id="
										+ useO.getId());
						dataList.add(dataMap);
					}
				}
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("item", dataList);
				map.put("link_url",RequestUtils.getRequestPath(null)+ "/repayment/repay-type" );
				map.put("page", page.getCurrentPage());
				map.put("pageSize", page.getPageSize());
				map.put("pageTotal", page.getTotalResultSize());
				json.put("data", map);
				code = Status.SUCCESS.getName();
				msg = "获取成功";
			} else {
				msg = "请先登录";
			}
		} catch (Exception e) {
			e.printStackTrace();
			code = Status.ERROR.getName();
			msg = "系统异常";

		} finally {
			json.put("code", code);
			json.put("message", msg);
			JSONUtil.toObjectJson(response, JSONUtil.beanToJson(json));
		}

	}


	/**
	 * 获取用户个人中心借款列表
	 *
	 * @param request
	 * @param response
	 * @param model
	 */

	@RequestMapping("credit-loan/get-my-loan")
	public void getMyLoans(HttpServletRequest request, HttpServletResponse response, Model model) {
		Map<String, Object> json = new HashMap<String, Object>();
		HashMap<String, Object> params = this.getParametersO(request);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String code = Status.FAILD.getName();
		String msg = "获取失败";
		try {
			User user = this.loginFrontUserByDeiceId(request);
//			user = new User();
//			user.setId("273");
			if (user != null) {
				params.put("userId", user.getId());
//				params.put("limit", 1);
				Integer[] statuses = new Integer[]{STATUS_DCS,STATUS_CSTG,STATUS_FSTG,STATUS_FKZ,STATUS_FKSB,STATUS_HKZ,STATUS_BFHK,STATUS_YYQ,STATUS_YHZ};
				params.put("statuses", statuses);
				List<Map<String, Object>> repayments = repaymentService.findMyLoan(params);
				for(Map<String, Object> tMap : repayments){
					String textTip = borrowStatusMap_front.get(Integer.parseInt(tMap.get("status").toString()));
					tMap.put("text_tip", "<font color='#ff8003' size='3'>" + textTip + "</font>");
					tMap.put("interests", 0);
					tMap.put("url", RequestUtils.getRequestPath(null) + "/repayment/detail.do?id=" + tMap.get("asset_order_id"));
					if(null != tMap.get("plan_fee_time")){
						tMap.put("plan_fee_time", sdf.format((Date)tMap.get("plan_fee_time")));
					}
					tMap.put("debt", new DecimalFormat("0.00").format(Integer.parseInt(tMap.get("debt").toString()) / 100.00));
					tMap.put("principal", new DecimalFormat("0.00").format(Integer.parseInt(tMap.get("principal").toString()) / 100.00));
					tMap.put("counter_fee", new DecimalFormat("0.00").format(Integer.parseInt(tMap.get("counter_fee").toString()) / 100.00));
					tMap.put("receipts", new DecimalFormat("0.00").format(Integer.parseInt(tMap.get("receipts").toString()) / 100.00));
					if(null != tMap.get("late_fee")) {
						tMap.put("late_fee", new DecimalFormat("0.00").format(Integer.parseInt(tMap.get("late_fee").toString()) / 100.00));
					}
					else{
						tMap.put("late_fee", "0.00");
					}
				}

				Map<String, Object> data = new HashMap<String, Object>();

				List<Map<String, Object>> payList = new ArrayList<Map<String, Object>>();
				Map<String, Object> mapPay = new HashMap<String, Object>();
				mapPay.put("type", 1);
				mapPay.put("title", "主动还款(银行卡)");
				mapPay.put("img_url", RequestUtils.getRequestPath(null) + "/common/web/images/union_pay_new.png");
				mapPay.put("link_url", RequestUtils.getRequestPath(null) + "/gotoRepaymentType?type=1");
				payList.add(mapPay);
				
				mapPay = new HashMap<String, Object>();
				mapPay.put("type", 2);
				mapPay.put("title", "自动扣款(银行卡)");
				mapPay.put("img_url", RequestUtils.getRequestPath(null) + "/common/web/images/self_motion.png");
				mapPay.put("link_url", RequestUtils.getRequestPath(null) + "/gotoRepaymentType?type=2");
				payList.add(mapPay);
				/*mapPay = new HashMap<String, Object>();
				mapPay.put("type", 3);
				mapPay.put("title", "扫码还款(支持支付宝、微信)");
				mapPay.put("img_url", RequestUtils.getRequestPath(null) + "/common/web/images/sao_code.png");
				mapPay.put("link_url", RequestUtils.getRequestPath(null) + "/gotoRepaymentType?type=3");
				payList.add(mapPay);*/
				/*mapPay = new HashMap<String, Object>();
				mapPay.put("type", 3);
				mapPay.put("title", "支付宝转账");
				mapPay.put("img_url", RequestUtils.getRequestPath(null) + "/common/web/images/alipay_card_info.png");
				mapPay.put("link_url", RequestUtils.getRequestPath(null) + "/gotoRepaymentType?type=3");
				payList.add(mapPay);*/
				/*Map<String, Object> mapPay = new HashMap<String, Object>();
				mapPay.put("type", 1);
				mapPay.put("title", "银行卡还款");
				mapPay.put("img_url", RequestUtils.getRequestPath(null) + "/common/web/images/union_pay.png");
				mapPay.put("link_url", RequestUtils.getRequestPath(null) + "/repayment/repay-type");
				payList.add(mapPay);
				mapPay = new HashMap<String, Object>();
				mapPay.put("type", 2);
				mapPay.put("title", "支付宝转账");
				mapPay.put("img_url", RequestUtils.getRequestPath(null) + "/common/web/images/alipay_card_info.png");
				mapPay.put("link_url", RequestUtils.getRequestPath(null) + "/repayment/repay-type");
				payList.add(mapPay);*/
//				mapPay = new HashMap<String, Object>();
//				mapPay.put("type", 3);
//				mapPay.put("title", "微信转账");
//				mapPay.put("img_url", RequestUtils.getRequestPath(null) + "/common/web/images/wechat.png");
//				mapPay.put("link_url", RequestUtils.getRequestPath(null) + "/repayment/repay-type");
//				payList.add(mapPay);

				Map<String, Object> item = new HashMap<String, Object>();
				item.put("list", repayments);
				item.put("pay_title", "支持多种还款方式，方便快捷");
				item.put("count", repayments.size());
				item.put("old_path", RequestUtils.getRequestPath(null) + "/content/Olduser");
				item.put("pay_type", payList);

				data.put("item", item);
				json.put("data", data);
				code = Status.SUCCESS.getName();
				msg = "获取成功";
			} else {
				code=Status.LOGIN.getName();
				msg = "请先登录";
			}
		} catch (Exception e) {
			e.printStackTrace();
			code = Status.ERROR.getName();
			msg = "系统异常";

		} finally {
			json.put("code", code);
			json.put("message", msg);
			JSONUtil.toObjectJson(response, JSONUtil.beanToJson(json));
		}

	}

	/**
	 * 获取用户个人中心借款列表详情
	 * 
	 * @param request
	 * @param response
	 * @param model
	 */

	@RequestMapping("mobile/web/loan/loan-detail")
	public void loanDetail(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Map<String, Object> json = new HashMap<String, Object>();
		HashMap<String, Object> params = this.getParametersO(request);
		String code = Status.FAILD.getName();
		String msg = "获取失败";
		Map<String, Object> dataMap = null;

		try {
			if (request.getParameter("id") == null
					|| request.getParameter("id") == "") {
				code = Status.FAILD.getName();
				msg = "请求参数错误！";
				logger.error("get loan-detail error:id  is null");
				return;
			}
			Integer id = Integer.valueOf(request.getParameter("id").toString());
			UserOrder userOrder = userOrderService.findById(id);

			if (userOrder != null) {
				HashMap<String, Object> userparams = new HashMap<String, Object>();
				// 查询用户的借款入账账户信息
				userparams.put("userId", userOrder.getUserId()); // user.getId()
				userparams.put("type", "2"); // 借记卡
				List<UserCardInfo> cardInfo = userBankService
						.findUserCardByUserId(userparams);
				UserCardInfo info = new UserCardInfo();
				if (cardInfo != null && cardInfo.size() > 0) {
					info = cardInfo.get(0);
				}

				dataMap = new HashMap<String, Object>();
				dataMap.put("status", userOrder.getStatus());// 状态
				dataMap.put("2", "公司还款成功，又积攒了一份信用");
				dataMap.put("打款成功", "打款成功");// 打款成功
				dataMap.put("审核通过", "审核通过");// 审核通过
				dataMap.put("申请提交成功", "申请提交成功");// 申请提交成功
				dataMap.put("moneyAmount", userOrder.getMoneyAmount());// 借款金额
				dataMap.put("intoMoney", userOrder.getIntoMoney());// 实际到账
				dataMap.put("loanInterests", userOrder.getLoanInterests());// 服务费用
				dataMap.put("借款期限", "借款期限");// 借款期限
				dataMap.put("orderTime", userOrder.getOrderTime() == null
						? ""
						: sdf.format(userOrder.getOrderTime()));// 申请日期
				dataMap.put(
						"receiveCardId",
						info.getCard_no() == null ? info.getBankName() : info
								.getBankName()
								+ "("
								+ info.getBankName().substring(
										info.getBankName().length() - 4,
										info.getBankName().length()) + ")");// 收款银行
			}

			json.put("data", dataMap);
			code = Status.SUCCESS.getName();
			msg = "获取成功";
			logger.info("get loan-detail success");
		} catch (Exception e) {
			logger.error("get loan-detail error", e);
			code = Status.ERROR.getName();
			msg = "系统异常";

		} finally {
			json.put("code", code);
			json.put("message", msg);
			JSONUtil.toObjectJson(response, JSONUtil.beanToJson(json));
		}

	}

}
